package com.atguigu.eduservice.service.impl;

import com.atguigu.eduservice.entity.EduCourse;
import com.atguigu.eduservice.entity.EduCourseDescription;
import com.atguigu.eduservice.entity.frontvo.CourseFrontVo;
import com.atguigu.eduservice.entity.frontvo.CourseWebVo;
import com.atguigu.eduservice.entity.vo.CourseInfoVo;
import com.atguigu.eduservice.entity.vo.CoursePublishVo;
import com.atguigu.eduservice.mapper.EduCourseMapper;
import com.atguigu.eduservice.service.EduChapterService;
import com.atguigu.eduservice.service.EduCourseDescriptionService;
import com.atguigu.eduservice.service.EduCourseService;
import com.atguigu.eduservice.service.EduVideoService;
import com.atguigu.servicebase.exceptionhandler.GuliException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 课程 服务实现类
 * </p>
 *
 * @author testjava
 * @since 2021-03-13
 */
@Service
public class EduCourseServiceImpl extends ServiceImpl<EduCourseMapper, EduCourse> implements EduCourseService {

    @Autowired
    private EduCourseDescriptionService courseDescriptionService;

    @Autowired
    private EduVideoService eduVideoService;

    @Autowired
    private EduChapterService eduChapterService;

    @Autowired
    private EduCourseDescriptionService eduCourseDescriptionService;

    //添加课程基本信息的方法
    //把表单提交过来的数据添加到课程表和课程描述表中
    @Override
    public String saveCourseInfo(CourseInfoVo courseInfoVo) {
        //1，向课程表添加课程基本信息
        EduCourse eduCourse = new EduCourse();
        BeanUtils.copyProperties(courseInfoVo,eduCourse);
        int insert = baseMapper.insert(eduCourse);

        if(insert <= 0){
            throw new GuliException(20001,"添加课程信息失败");
        }

        //获取添加之后的id
        String cid = eduCourse.getId();


        //2，向课程简介表添加课程简介
        //mybatisPlus中mapper层，service层都有操作数据库的方法
        EduCourseDescription courseDescription = new EduCourseDescription();
        //课程简介Description
        courseDescription.setDescription(courseInfoVo.getDescription());
        //设置描述id就是课程id
        courseDescription.setId(cid);
        courseDescriptionService.save(courseDescription);

        //返回id
        return cid;
    }

    //根据课程id查询课程基本信息
    @Override
    public CourseInfoVo getCourseInfo(String courseId) {
        //1，查询课程表
        EduCourse eduCourse = baseMapper.selectById(courseId);
        CourseInfoVo courseInfoVo = new CourseInfoVo();
        BeanUtils.copyProperties(eduCourse,courseInfoVo);

        //2，查询描述表
        EduCourseDescription courseDescription = courseDescriptionService.getById(courseId);
        courseInfoVo.setDescription(courseDescription.getDescription());

        return courseInfoVo;
    }

    //修改课程信息
    @Override
    public void updateCourseInfo(CourseInfoVo courseInfoVo) {
        //1，修改课程表
        EduCourse eduCourse = new EduCourse();
        BeanUtils.copyProperties(courseInfoVo,eduCourse);
        int update = baseMapper.updateById(eduCourse);
        //baseMapper.updateById(eduCourse),传入的实体类必须数据表必须有ID列

        if(update == 0){
            throw new GuliException(20001,"修改课程信息失败");
        }

        //2，修改描述表
        EduCourseDescription courseDescription = new EduCourseDescription();
        BeanUtils.copyProperties(courseInfoVo,courseDescription);
        courseDescriptionService.updateById(courseDescription);
    }

    //根据课程id查询课程确认信息

    /**
     *  public class ServiceImpl<M extends BaseMapper<T>, T> implements IService<T> {
     *     @Autowired
     *     protected M baseMapper;
     *     ...
     *
     *  通过源码，M extends BaseMapper，M继承了BaseMapper，当我么mapper层中“M”继承了BaseMapper
     *      所以，ServiceImpl自动注入了mapper层的接口，属性名叫baseMapper，
     *      故可以用baseMapper调用BaseMapper以及mapper层自己写的方法
     */
    @Override
    public CoursePublishVo getPublishCourseInfo(String id) {
        //baseMapper调mapper层的相关方法
        CoursePublishVo publishCourseInfo = baseMapper.getPublishCourseInfo(id);
        return publishCourseInfo;
    }

    //删除课程(因为课程与章节、小节、描述之间有外键关系，虽然设计数据库时没有外键关系，但我们删除课程时
    //应该遵循从小到大的关系逐一删除)
    @Override
    public void removeCourse(String courseId) {
        //1，根据课程id删除小节
        eduVideoService.removeVideoByCourseId(courseId);
        //2，根据课程id删除章节
        eduChapterService.removeChapterByCourseId(courseId);
        //3，根据课程id删除描述(描述信息直接删除，因为描述表与课程表是一一对应的关系)
        eduCourseDescriptionService.removeById(courseId);
        //4，根据课程id删除课程本身
        int result = baseMapper.deleteById(courseId);

        if(result == 0 ){
            throw new GuliException(20001,"删除失败");
        }
    }

    //1，条件查询分页查询课程（前台）
    @Override
    public Map<String, Object> getCourseFrontList(Page<EduCourse> pageCourse,CourseFrontVo courseFrontVo) {
        //根据讲师id查询所讲课程

        QueryWrapper<EduCourse> wrapper = new QueryWrapper<>();
        //判断条件值是否为空，不为空拼接
        if(!StringUtils.isEmpty(courseFrontVo.getSubjectParentId())){ //一级分类
            wrapper.eq("subject_parent_id",courseFrontVo.getSubjectParentId());
        }
        if(!StringUtils.isEmpty(courseFrontVo.getSubjectId())){ //二级分类
            wrapper.eq("subject_id",courseFrontVo.getSubjectId());
        }
        if(!StringUtils.isEmpty(courseFrontVo.getBuyCountSort())) { //关注度
            wrapper.orderByDesc("buy_count");
        }
        if(!StringUtils.isEmpty(courseFrontVo.getGmtCreateSort())) { //最新
            wrapper.orderByDesc("gmt_create");
        }

        if(!StringUtils.isEmpty(courseFrontVo.getPriceSort())) {//价格
            wrapper.orderByDesc("price");
        }

        baseMapper.selectPage(pageCourse,wrapper);

        List<EduCourse> records = pageCourse.getRecords();
        long current = pageCourse.getCurrent();
        long pages = pageCourse.getPages();
        long size = pageCourse.getSize();
        long total = pageCourse.getTotal();
        boolean hasNext = pageCourse.hasNext();//下一页
        boolean hasPrevious = pageCourse.hasPrevious();//上一页

        //把分页数据获取出来，放到map集合
        Map<String, Object> map = new HashMap<>();
        map.put("items", records);
        map.put("current", current);
        map.put("pages", pages);
        map.put("size", size);
        map.put("total", total);
        map.put("hasNext", hasNext);
        map.put("hasPrevious", hasPrevious);

        //map返回
        return map;
    }

    //根据课程id，编写sql语句查询课程信息
    @Override
    public CourseWebVo getBaseCourseInfo(String courseId) {
        return baseMapper.getBaseCourseInfo(courseId);
    }
}
